package com.dana.gomoku.api;

import com.dana.gomoku.constant.Constants;
import com.dana.gomoku.game.GameReadyResponse;
import com.dana.gomoku.game.GameResponse;
import com.dana.gomoku.mapper.UserMapper;
import com.dana.gomoku.match.OnlineUserManager;
import com.dana.gomoku.model.User;
import com.dana.gomoku.room.Room;
import com.dana.gomoku.room.RoomManager;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;

@Slf4j
@Component
public class GameAPI extends TextWebSocketHandler {

    @Autowired
    OnlineUserManager onlineUserManager;
    @Autowired
    RoomManager roomManager;
    @Autowired
    UserMapper userMapper;
    private ObjectMapper objectMapper=new ObjectMapper();
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        GameReadyResponse resp=new GameReadyResponse();
        //1.获取当前玩家
        User user=(User) session.getAttributes().get(Constants.USER_SESSION_KEY);
        //判断当前玩家是不是空
        if (user==null){
            resp.setOk(false);
            resp.setReason("您尚未登录");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(resp)));
            return;
        }
        //2.判断是不是多开,在游戏大厅登录并且在游戏房间内也登录也算多开
        if (onlineUserManager.getFromGameHall(user.getUserId())!=null||
            onlineUserManager.getFromGameRoom(user.getUserId())!=null){
            resp.setReason("您已经登录了");
            resp.setOk(false);
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(resp)));
            return;
        }
        //3.判断当前玩家是不是已经进入了房间
        Room room = roomManager.getRoomByUserId(user.getUserId());
        if (room==null){
            resp.setOk(false);
            resp.setReason("用户尚未进入房间");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(resp)));
            return;
        }
        //4.让当前玩家在游戏房间内上线
        onlineUserManager.enterGameRoom(user.getUserId(),session);
        log.info("玩家 {}  进入游戏房间",user.getUsername());

        //5.把两个玩家加入到房间
        //现在把两个玩家加入是因为如果之前在匹配的时候加入跳转到游戏房间页面的时候可能有玩家掉线了
        //在游戏房间内加入玩家,就避免了页面跳转带来的问题
        synchronized (room){
            if (room.getUser1()==null){
                room.setUser1(user);
                log.info("第一个进入房间的玩家是 {}",room.getUser1());
                //先进入的玩家执白子(先手权)
                room.setWhiteUser(user.getUserId());
                return;

            }
            if (room.getUser2()==null){
                room.setUser2(user);
                log.info("第二个进入房间的玩家是 {}",room.getUser2());

                //两个玩家都加入游戏后,开始加载游戏,就像lol,10个玩家全部读条完毕,进入游戏
                //通知玩家一
                noticeGameReady(room,room.getUser1(),room.getUser2());
                //通知玩家二
                noticeGameReady(room,room.getUser2(),room.getUser1());
                return;
            }
            resp.setOk(false);
            resp.setReason("当前房间已经满了");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(resp)));
        }

    }

    private void noticeGameReady(Room room, User thisUser, User thatUser) throws IOException {
        GameReadyResponse response=new GameReadyResponse();
        response.setMessage("gameReady");
        response.setRoomId(room.getRoomId());
        response.setReason("");
        response.setOk(true);
        response.setThisUserId(thisUser.getUserId());
        response.setThatUserId(thatUser.getUserId());
        response.setWhiteUser(room.getWhiteUser());
        // 把当前的响应数据传回给玩家.
        WebSocketSession webSocketSession = onlineUserManager.getFromGameRoom(thisUser.getUserId());
        webSocketSession.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //1.获取当前对象
        User user= (User) session.getAttributes().get(Constants.USER_SESSION_KEY);
        WebSocketSession CurSession = onlineUserManager.getFromGameRoom(user.getUserId());
        if (CurSession==null){
            return;
        }
        Room room = roomManager.getRoomByUserId(user.getUserId());
        room.putChess(message.getPayload());
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        //1.获取当前对象
        User user= (User) session.getAttributes().get(Constants.USER_SESSION_KEY);
        //2.看当前玩家是否在房间内
        WebSocketSession exitSession = onlineUserManager.getFromGameRoom(user.getUserId());
        //3.如果当前会话和之前存储的是同一个会话我们再进行下线
        if (exitSession==session){
            onlineUserManager.exitGameRoom(user.getUserId());
            log.info("当前玩家 {}  离开房间",user.getUsername());
        }
        noticeThatUserWin(user);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        //1.获取当前对象
        User user= (User) session.getAttributes().get(Constants.USER_SESSION_KEY);
        //2.看当前玩家是否在房间内
        WebSocketSession exitSession = onlineUserManager.getFromGameRoom(user.getUserId());
        //3.如果当前会话和之前存储的是同一个会话我们再进行下线
        if (exitSession==session){
            onlineUserManager.exitGameRoom(user.getUserId());
            log.info("当前玩家 {}  离开房间",user.getUsername());
        }
        noticeThatUserWin(user);
    }

    private void noticeThatUserWin(User user) throws IOException {
        // 1. 根据当前玩家, 找到玩家所在的房间
        Room room = roomManager.getRoomByUserId(user.getUserId());
        if (room == null) {
            // 这个情况意味着房间已经被释放了, 也就没有 "对手" 了
            System.out.println("当前房间已经释放, 无需通知对手!");
            return;
        }

        // 2. 根据房间找到对手
        User thatUser = (user == room.getUser1()) ? room.getUser2() : room.getUser1();
        // 3. 找到对手的在线状态
        WebSocketSession webSocketSession = onlineUserManager.getFromGameRoom(thatUser.getUserId());
        if (webSocketSession == null) {
            // 这就意味着对手也掉线了!
            System.out.println("对手也已经掉线了, 无需通知!");
            return;
        }
        // 4. 构造一个响应, 来通知对手, 你是获胜方
        GameResponse resp = new GameResponse();
        resp.setMessage("putChess");
        resp.setUserId(thatUser.getUserId());
        resp.setWinner(thatUser.getUserId());
        webSocketSession.sendMessage(new TextMessage(objectMapper.writeValueAsString(resp)));

        // 5. 更新玩家的分数信息
        int winUserId = thatUser.getUserId();
        int loseUserId = user.getUserId();
        userMapper.userWin(winUserId);
        userMapper.userLose(loseUserId);

        // 6. 释放房间对象
        roomManager.remove(room.getRoomId(), room.getUser1().getUserId(), room.getUser2().getUserId());
    }
}
